let xmlhttp;
let formdata;
if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest;
} else {
    xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}

function uploadimg() {
    let msg = document.getElementById('msg');
    let cid = document.getElementById('cid').value;
    let img = document.getElementById('img').value;
    let title = document.getElementById('title').value;
    let href = document.getElementById('href').value;
    xmlhttp.onreadystatechange = () => {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            msg.innerHTML = JSON.parse(xmlhttp.responseText).msg;
            if (JSON.parse(xmlhttp.responseText).code === 200) {
                showimg();
            }
        }
    }
    xmlhttp.open('POST', 'http://127.0.0.1:8080/v1/maps/upload', true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    formdata = `cid=${cid}&img=${img}&title=${title}&href=${href}`;
    xmlhttp.send(formdata);
}

function showimg() {
    let html = "";
    let mapsmsg = document.getElementById('maps');
    xmlhttp.onreadystatechange = () => {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let maps = JSON.parse(xmlhttp.responseText);
            // console.log('maps: ', maps);
            for (let i = 0; i < maps.length; i++) {
                html += `<tr>
                            <td>${maps[i].cid}</td>
                            <td>${maps[i].img}</td>
                            <td>${maps[i].title}</td>
                            <td>${maps[i].href}</td>
                            <td><a href="javascript:delm(${maps[i].cid})">删除</a></td>
                            <td><a href="javascript:updateTab(${maps[i].cid})">修改</a></td>
                            <td><a href="javascript:upBanner(${maps[i].cid})">上传轮播图</a></td>
                            </tr>`;
            }
            mapsmsg.innerHTML = html;
        }
    }
    xmlhttp.open('GET', 'http://127.0.0.1:8080/v1/maps/list', true);
    xmlhttp.send();
}

function delm(cid) {
    if (!confirm('是否删除编号为' + cid + '的图片信息')) {
        return;
    }
    xmlhttp.onreadystatechange = () => {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let sta = JSON.parse(xmlhttp.responseText).code;
            if (sta == 200) {
                showimg();
                alert('编号为' + cid + '的信息删除成功！')
            } else {
                alert('删除失败！')
            }
        }
    }
    let url = "http://127.0.0.1:8080/v1/maps/delete" + cid;
    xmlhttp.open('DELETE', url, true);
    xmlhttp.send();
}

function updateTab(cid) {
    let html = '';
    let url = "http://127.0.0.1:8080/v1/maps/find" + cid;
    let upda = document.getElementById('upda');
    xmlhttp.onreadystatechange = () => {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            let imgObj = JSON.parse(xmlhttp.responseText);
            html = ` <form action="#" method="POST" >
        <fieldset class="upl">
            <legend>
                <h3>修改轮播图${cid}的信息 </h3>
            </legend>
            图片路径：
            <input id="uimg" name="uimg" value="${imgObj[0].img}" type="text" class="form-control"><br>
            图片标题：
            <input id="utitle" name="utitle" value="${imgObj[0].title}" type="text" class="form-control"><br>
            图片引用：
            <input id="uhref" name="uhref" value="${imgObj[0].href}" type="text" class="form-control"><br>
            <input class="btn btn-primary" type="button" value="修改" onclick="updateimg(${cid})" >
            <h3>提示信息</h3>
            <h3 id="umsg" style="color: red;"></h3>
        </fieldset>
    </form>`;
            upda.innerHTML = html;
        }
    }
    xmlhttp.open('GET', url, true);
    xmlhttp.send();
}

function updateimg(cid) {
    let formdata;
    let uimg = document.getElementById('uimg').value;
    let utitle = document.getElementById('utitle').value;
    let uhref = document.getElementById("uhref").value
    let umsg = document.getElementById('umsg');
    xmlhttp.onreadystatechange = () => {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            umsg.innerHTML = JSON.parse(xmlhttp.responseText).msg;
            if (JSON.parse(xmlhttp.responseText).code === 200) {
                showimg();
            }
        }
    }
    xmlhttp.open('PUT', "http://127.0.0.1:8080/v1/maps/update", 'true');
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    formdata = `cid=${cid}&img=${uimg}&title=${utitle}&href=${uhref}`;
    if (!confirm(`是否要修改编号${cid}的轮播图信息？`)) {
        return;
    }
    xmlhttp.send(formdata);
}

// 显示修改图片的页面布局
function upBanner(cid) {
    // console.log('scid: ', cid);
    let html = `<div style="width:100px">
    <img width="80px" src="" alt="">
    <input type="file" οnchange="sendFile()" id="up" name="up" />
    </div>
    <input type="button" name="" value="提交" id="" onclick="sendFile(${cid})">`;
    $('#upbanner').html(html);
    let $img = document.getElementsByTagName("img")[0];
    let $input = document.getElementsByName("up")[0];
    $input.addEventListener("change", changeHandler);
    function changeHandler() {
      //显示选中的图片
      let f = $input.files[0];
      let src = window.URL.createObjectURL(f);
      $img.src = src;
    }
}

// 上传轮播图
function sendFile(cid) {
    console.log('scid: ', cid);
    var fd = new FormData();
    var pic = document.getElementById("up").files[0];
    var type = pic.type; //文件类型

    if (type != "image/jpeg" && type != "image/png") {
      alert("请上传正确格式图片");
      return false;
    }

    var size = parseInt(pic.size) / 1024 / 1024; //文件大小（换算成 M）

    if (size > 5) {
      alert('文件过大');
      return false;
    }

    fd.append(pic.name, pic);
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        let msg = xhr.responseText;
        // console.log('msg: ', msg);
        alert(msg);
        showimg();
      }
    }
    let url = "http://127.0.0.1:8080/v1/maps/upimg?cid="+cid;
    xhr.open("POST", url, true);
    xhr.send(fd);
  }